<template>
  <div id="rolelist">
    <div class="tools">
      <el-button type="primary" @click="addRole">新建角色</el-button>
    </div>
    <el-table v-loading="loading" row-key="id" :data="roleList" style="width: 100%">
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="角色名称" align="left">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handleEdit(scope.row.id)">{{scope.row.roleName}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="角色编号" align="left"></el-table-column>
      <el-table-column fixed="right" label="操作" width="90" align="center">
        <template #default="scope">
          <el-button size="small" icon="EditPen" type="primary" plain circle @click="handleEdit(scope.row.id)"></el-button>
          <el-button size="small" icon="Delete" type="danger" plain circle @click="handleDelete(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
let { proxy }: any = getCurrentInstance();
let loading = ref(false);
let roleList: any = reactive([]);

onMounted(() => {
  findRoleList();
});

function findRoleList() {
  roleList.length = 0;
  loading.value = true;
  const url = '/api/sys/findRoleList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      loading.value = false;
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        roleList.push(...res.data.roleList);
      }
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}

function addRole() {
  proxy.$router.push('/rolesave');
}

function handleEdit(id: string) {
  proxy.$router.push({ path: '/rolesave', query: { id } });
}

function handleDelete(id: string) {
  proxy
    .$confirm('确定删除此角色?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deleteRole';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findRoleList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
</script>
